package org.lee.web.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import org.lee.common.constant.CacheConstants;
import org.lee.common.constant.Constants;
import org.lee.common.core.service.redis.RedisService;
import org.lee.common.core.vo.response.AjaxResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;

@Component
public class CaptchaService {

    @Inject
    private Producer captchaProducer;

    @Inject("captchaProducerMath")
    private Producer captchaProducerMath;

    @Inject
    private RedisService redisService;

    @Inject("${lee.captcha-type}")
    private String captchaType;

    @Inject("${lee.captcha-enabled}")
    private boolean captchaEnabled;

    public AjaxResult getCode() {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr;
        String code;
        BufferedImage image;

        // 生成验证码
        if (CharSequenceUtil.equals("math", captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        } else {
            return AjaxResult.error("不支持的验证码类型");
        }

        redisService.setCacheObject(verifyKey, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }
}
